<template>
  <view class="store-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">门店管理</text>
        <view class="header-actions">
          <uni-icons type="search" size="20" color="#fff" @click="toggleSearch" />
        </view>
      </view>
    </view>

    <!-- 数据概览卡片 -->
    <view class="overview-section">
      <view class="overview-card">
        <view class="overview-item">
          <text class="overview-value">{{ storeList.length }}</text>
          <text class="overview-label">门店总数</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ activeStoreCount }}</text>
          <text class="overview-label">营业中</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ closedStoreCount }}</text>
          <text class="overview-label">已关闭</text>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section" v-if="showSearch">
      <view class="search-card">
        <uni-easyinput
          prefixIcon="search"
          v-model="searchKeyword"
          placeholder="输入门店名称或地址搜索"
          @input="handleSearchInput"
          @confirm="handleSearch"
          @iconClick="handleSearch"
          clearable
        ></uni-easyinput>
      </view>
    </view>

    <!-- 功能模块网格 -->
    <view class="modules-section">
      <view class="modules-grid">
        <view 
          class="module-card" 
          v-for="module in modules" 
          :key="module.key"
          @click="navigateToModule(module)"
        >
          <view class="module-icon">
            <uni-icons :type="module.icon" size="32" :color="module.color" />
          </view>
          <text class="module-title">{{ module.title }}</text>
          <text class="module-desc">{{ module.desc }}</text>
          <view class="module-badge" v-if="module.badge">
            <text class="badge-text">{{ module.badge }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 快捷操作区 -->
    <view class="quick-actions">
      <text class="section-title">快捷操作</text>
      <scroll-view class="actions-scroll" scroll-x>
        <view class="actions-list">
          <view class="action-item" @click="navigateToDetail()">
            <view class="action-icon">
              <uni-icons type="plus" size="24" color="#1890FF" />
            </view>
            <text class="action-text">新增门店</text>
          </view>
          <view class="action-item" @click="handleBatchOperation">
            <view class="action-icon">
              <uni-icons type="checkbox" size="24" color="#1890FF" />
            </view>
            <text class="action-text">批量操作</text>
          </view>
          <view class="action-item" @click="handleStatusManage">
            <view class="action-icon">
              <uni-icons type="gear" size="24" color="#1890FF" />
            </view>
            <text class="action-text">状态管理</text>
          </view>
          <view class="action-item" @click="handleDataExport">
            <view class="action-icon">
              <uni-icons type="download" size="24" color="#1890FF" />
            </view>
            <text class="action-text">数据导出</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-section">
      <text class="section-title">状态筛选</text>
      <view class="filter-card">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-tags">
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === undefined }"
              @click="handleStatusFilter(undefined)"
            >
              全部
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 1 }"
              @click="handleStatusFilter(1)"
            >
              营业中
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 0 }"
              @click="handleStatusFilter(0)"
            >
              已关闭
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 2 }"
              @click="handleStatusFilter(2)"
            >
              装修中
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 门店列表 -->
    <view class="store-list-section">
      <text class="section-title">门店列表</text>
      <scroll-view
        scroll-y
        class="store-list-scroll"
        refresher-enabled
        @refresherrefresh="handleRefresh"
        :refresher-triggered="isRefreshing"
        @scrolltolower="handleLoadMore"
      >
        <view v-if="storeList.length > 0" class="store-list">
          <view
            class="store-card"
            v-for="store in storeList"
            :key="store.id"
            @click="navigateToDetail(store.id)"
          >
            <view class="store-header">
              <view class="store-info">
                <text class="store-name">{{ store.name }}</text>
                <text class="store-type">{{ store.store_type || '综合门店' }}</text>
              </view>
              <view class="store-status">
                <uni-tag 
                  :text="getStatusText(store.status)" 
                  :type="getStatusType(store.status)" 
                  size="small" 
                />
              </view>
            </view>
            
            <view class="store-details">
              <view class="detail-row">
                <view class="detail-item">
                  <uni-icons type="location" size="14" color="#999"></uni-icons>
                  <text class="detail-text">{{ store.address }}</text>
                </view>
              </view>
              
              <view class="detail-row">
                <view class="detail-item">
                  <uni-icons type="phone" size="14" color="#999"></uni-icons>
                  <text class="detail-text">{{ store.phone || '暂无电话' }}</text>
                </view>
                <view class="detail-item">
                  <uni-icons type="person" size="14" color="#999"></uni-icons>
                  <text class="detail-text">{{ store.manager || '暂无负责人' }}</text>
                </view>
              </view>
              
              <view class="detail-row" v-if="store.business_hours">
                <view class="detail-item">
                  <uni-icons type="clock" size="14" color="#999"></uni-icons>
                  <text class="detail-text">{{ formatBusinessHours(store.business_hours) }}</text>
                </view>
              </view>
            </view>

            <view class="store-actions" @click.stop>
              <button 
                class="action-btn primary" 
                @click="navigateToVenues(store)"
              >
                场地管理
              </button>
              <button class="action-btn secondary" @click="showActionSheet(store)">
                更多
              </button>
            </view>
          </view>
        </view>
        
        <uni-load-more v-if="storeList.length > 0 || loading" :status="loadingStatus"></uni-load-more>
        
        <view v-if="storeList.length === 0 && !loading" class="empty-container">
          <uni-icons type="shop" size="60" color="#999"></uni-icons>
          <text class="empty-text">暂无门店</text>
          <button class="add-store-btn" @click="navigateToDetail()">添加门店</button>
        </view>
      </scroll-view>
    </view>

    <!-- 状态切换弹窗 -->
    <uni-popup ref="statusPopup" type="bottom">
      <view class="status-modal">
        <view class="modal-header">
          <text class="modal-title">切换门店状态</text>
          <uni-icons type="close" size="20" @click="closeStatusModal"></uni-icons>
        </view>
        <view class="status-options">
          <view 
            v-for="status in statusOptions" 
            :key="status.value"
            class="status-option"
            @click="changeStoreStatus(status.value)"
          >
            <uni-tag :text="status.text" :type="status.type" size="small" />
            <text class="status-desc">{{ status.desc }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { fetchStores, updateStore } from '@/api/store';
import type { Store, StoreQuery } from '@/types/store';

const storeList = ref<Store[]>([]);
const showSearch = ref(false);
const searchKeyword = ref('');
const queryParams = reactive<StoreQuery>({
  page: 1,
  pageSize: 10,
  name: '',
});

const loading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);
const statusPopup = ref<any>(null);
const currentStore = ref<Store | null>(null);

const loadingStatus = computed(() => {
  if (loading.value) return 'loading';
  return hasMore.value ? 'more' : 'noMore';
});

// 计算营业中门店数量
const activeStoreCount = computed(() => {
  return storeList.value.filter(store => store.status === 1).length;
});

// 计算已关闭门店数量
const closedStoreCount = computed(() => {
  return storeList.value.filter(store => store.status === 0).length;
});

// 功能模块配置
const modules = ref([
  {
    key: 'active',
    title: '营业门店',
    desc: '正常营业',
    icon: 'checkmarkempty',
    color: '#52C41A',
    badge: activeStoreCount.value > 0 ? activeStoreCount.value.toString() : '',
  },
  {
    key: 'closed',
    title: '关闭门店',
    desc: '暂停营业',
    icon: 'close',
    color: '#FF4D4F',
    badge: closedStoreCount.value > 0 ? closedStoreCount.value.toString() : '',
  },
  {
    key: 'management',
    title: '门店管理',
    desc: '综合管理',
    icon: 'gear',
    color: '#FA8C16',
    badge: '',
  },
  {
    key: 'statistics',
    title: '经营统计',
    desc: '数据分析',
    icon: 'bars',
    color: '#722ED1',
    badge: '',
  },
]);

// 状态选项
const statusOptions = [
  { value: 1, text: '营业中', type: 'success', desc: '门店正常营业' },
  { value: 0, text: '已关闭', type: 'error', desc: '门店暂停营业' },
  { value: 2, text: '装修中', type: 'warning', desc: '门店正在装修' },
];

// 获取状态文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.text : '未知';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.type : 'default';
};

// 获取门店列表
const getStoreList = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;

  if (isRefresh) {
    queryParams.page = 1;
  }

  try {
    const res = await fetchStores(queryParams);
    if (isRefresh) {
      storeList.value = res.list;
    } else {
      storeList.value = [...storeList.value, ...res.list];
    }
    hasMore.value = storeList.value.length < res.total;
    
    if (queryParams.page) {
      queryParams.page++;
    } else {
      queryParams.page = 2;
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    uni.showToast({ title: '获取门店列表失败', icon: 'none' });
  } finally {
    loading.value = false;
    isRefreshing.value = false;
  }
};

const handleRefresh = () => {
  isRefreshing.value = true;
  getStoreList(true);
};

const handleLoadMore = () => {
  if (hasMore.value && !loading.value) {
    getStoreList();
  }
};

const handleStatusFilter = (status: number | undefined) => {
  queryParams.status = status;
  getStoreList(true);
};

// 切换搜索栏显示
const toggleSearch = () => {
  showSearch.value = !showSearch.value;
};

// 防抖搜索
let searchTimer: any = null;
const debouncedSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  searchTimer = setTimeout(() => {
    handleSearch();
  }, 300);
};

const handleSearchInput = () => {
  debouncedSearch();
};

const handleSearch = () => {
  queryParams.name = searchKeyword.value;
  getStoreList(true);
};

const navigateToDetail = (id?: number) => {
  const url = id ? `/pages/stores/detail?id=${id}` : '/pages/stores/detail';
  uni.navigateTo({ url });
};

// 导航到场地管理
const navigateToVenues = (store: Store) => {
  uni.navigateTo({ url: `/pages/venues/index?storeId=${store.id}` });
};

// 导航到模块页面
const navigateToModule = (module: any) => {
  switch (module.key) {
    case 'active':
      queryParams.status = 1;
      getStoreList(true);
      break;
    case 'closed':
      queryParams.status = 0;
      getStoreList(true);
      break;
    case 'management':
      uni.showToast({ title: '门店管理功能开发中', icon: 'none' });
      break;
    case 'statistics':
      uni.showToast({ title: '统计功能开发中', icon: 'none' });
      break;
  }
};

// 显示操作菜单
const showActionSheet = (store: Store) => {
  currentStore.value = store;
  uni.showActionSheet({
    itemList: ['查看详情', '编辑门店', '场地管理', '切换状态', '删除门店'],
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          navigateToDetail(store.id);
          break;
        case 1:
          navigateToDetail(store.id);
          break;
        case 2:
          navigateToVenues(store);
          break;
        case 3:
          statusPopup.value?.open();
          break;
        case 4:
          handleDeleteStore(store);
          break;
      }
    }
  });
};

// 删除门店
const handleDeleteStore = (store: Store) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除门店"${store.name}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // await deleteStore(store.id);
          uni.showToast({ title: '删除成功' });
          getStoreList(true);
        } catch (error) {
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    }
  });
};

// 快捷操作处理函数
const handleBatchOperation = () => {
  uni.showToast({
    title: '批量操作功能开发中',
    icon: 'none'
  });
};

const handleStatusManage = () => {
  uni.showToast({
    title: '状态管理功能开发中',
    icon: 'none'
  });
};

const handleDataExport = () => {
  uni.showToast({
    title: '数据导出功能开发中',
    icon: 'none'
  });
};

// 关闭状态弹窗
const closeStatusModal = () => {
  statusPopup.value?.close();
};

// 切换门店状态
const changeStoreStatus = async (status: number) => {
  if (!currentStore.value) return;
  
  try {
    await updateStore(currentStore.value.id, { status });
    uni.showToast({ title: '状态更新成功' });
    closeStatusModal();
    getStoreList(true);
  } catch (error) {
    uni.showToast({ title: '状态更新失败', icon: 'none' });
  }
};

// 格式化营业时间显示
const formatBusinessHours = (businessHours: string) => {
  if (!businessHours) return '营业时间未设置';
  
  try {
    const data = JSON.parse(businessHours);
    
    // 简单模式
    if (data.workday && data.weekend) {
      const workdayText = data.workday.isOpen 
        ? `工作日 ${data.workday.openTime}-${data.workday.closeTime}`
        : '工作日休息';
      
      const weekendText = data.weekend.isOpen 
        ? `周末 ${data.weekend.openTime}-${data.weekend.closeTime}`
        : '周末休息';
      
      if (data.workday.isOpen && data.weekend.isOpen) {
        // 如果工作日和周末时间相同，简化显示
        if (data.workday.openTime === data.weekend.openTime && 
            data.workday.closeTime === data.weekend.closeTime) {
          return `每日 ${data.workday.openTime}-${data.workday.closeTime}`;
        }
        return `${workdayText}，${weekendText}`;
      } else if (data.workday.isOpen) {
        return workdayText;
      } else if (data.weekend.isOpen) {
        return weekendText;
      } else {
        return '暂停营业';
      }
    }
    
    // 高级模式
    if (data.daily && Array.isArray(data.daily)) {
      const openDays = data.daily.filter(day => day.isOpen);
      if (openDays.length === 0) {
        return '暂停营业';
      }
      
      // 检查是否所有营业日时间相同
      const firstOpenDay = openDays[0];
      const allSameTime = openDays.every(day => 
        day.openTime === firstOpenDay.openTime && 
        day.closeTime === firstOpenDay.closeTime
      );
      
      if (allSameTime && openDays.length === 7) {
        return `每日 ${firstOpenDay.openTime}-${firstOpenDay.closeTime}`;
      } else if (allSameTime) {
        const dayNames = openDays.map(day => day.dayName).join('、');
        return `${dayNames} ${firstOpenDay.openTime}-${firstOpenDay.closeTime}`;
      } else {
        // 时间不同，显示第一个营业日的时间
        return `${firstOpenDay.dayName} ${firstOpenDay.openTime}-${firstOpenDay.closeTime} 等`;
      }
    }
    
    return '营业时间格式错误';
  } catch (error) {
    console.error('解析营业时间失败:', error);
    return businessHours; // 解析失败时返回原始数据
  }
};

onShow(() => {
  getStoreList(true);
});
</script>

<style lang="scss" scoped>
.store-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1890FF 0%, #F0F9FF 30%);
}

.header {
  padding-top: var(--status-bar-height);
  background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
  
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
    }
  }
}

.overview-section {
  margin: -20rpx 32rpx 32rpx;
  
  .overview-card {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 20rpx rgba(24, 144, 255, 0.1);
    
    .overview-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
      
      .overview-value {
        font-size: 32rpx;
        font-weight: 600;
        color: #1890FF;
        margin-bottom: 8rpx;
      }
      
      .overview-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-section {
  padding: 0 32rpx 32rpx;
  
  .search-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  }
}

.modules-section {
  padding: 0 32rpx 32rpx;
  
  .modules-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    
    .module-card {
      position: relative;
      background: #fff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .module-icon {
        margin-bottom: 16rpx;
      }
      
      .module-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .module-desc {
        font-size: 24rpx;
        color: #999;
      }
      
      .module-badge {
        position: absolute;
        top: 16rpx;
        right: 16rpx;
        background: #FF4D4F;
        border-radius: 20rpx;
        padding: 4rpx 12rpx;
        
        .badge-text {
          font-size: 20rpx;
          color: #fff;
        }
      }
    }
  }
}

.quick-actions {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .actions-scroll {
    white-space: nowrap;
    
    .actions-list {
      display: flex;
      gap: 24rpx;
      padding-bottom: 16rpx;
      
      .action-item {
        flex-shrink: 0;
        background: #fff;
        border-radius: 12rpx;
        padding: 24rpx 32rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 120rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        
        .action-icon {
          margin-bottom: 12rpx;
        }
        
        .action-text {
          font-size: 24rpx;
          color: #333;
          white-space: nowrap;
        }
      }
    }
  }
}

.filter-section {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .filter-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .filter-scroll {
      white-space: nowrap;
      
      .filter-tags {
        display: flex;
        gap: 16rpx;
        
        .filter-tag {
          padding: 12rpx 24rpx;
          border-radius: 20rpx;
          background-color: #f5f5f5;
          color: #666;
          font-size: 24rpx;
          white-space: nowrap;
          transition: all 0.3s ease;
          
          &.active {
            background-color: #1890FF;
            color: #fff;
          }
        }
      }
    }
  }
}

.store-list-section {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .store-list-scroll {
    height: 600rpx;
  }
  
  .store-list {
    .store-card {
      background: #fff;
      border-radius: 16rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .store-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16rpx;
        
        .store-info {
          flex: 1;
          
          .store-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            display: block;
            margin-bottom: 8rpx;
          }
          
          .store-type {
            font-size: 24rpx;
            color: #666;
          }
        }
      }
      
      .store-details {
        margin-bottom: 16rpx;
        
        .detail-row {
          display: flex;
          align-items: center;
          margin-bottom: 12rpx;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .detail-item {
            display: flex;
            align-items: center;
            margin-right: 32rpx;
            font-size: 24rpx;
            color: #666;
            flex: 1;
            
            .detail-text {
              margin-left: 8rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }
      
      .store-actions {
        display: flex;
        gap: 16rpx;
        
        .action-btn {
          flex: 1;
          height: 64rpx;
          border-radius: 12rpx;
          font-size: 24rpx;
          
          &.primary {
            background-color: #1890FF;
            color: #fff;
          }
          
          &.secondary {
            background-color: #f5f5f5;
            color: #666;
          }
        }
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999;

  .empty-text {
    margin: 20rpx 0 40rpx;
    font-size: 28rpx;
  }
  
  .add-store-btn {
    padding: 20rpx 40rpx;
    background-color: #1890FF;
    color: #fff;
    border-radius: 12rpx;
    font-size: 24rpx;
  }
}

.status-modal {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  padding: 40rpx;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
    }
  }
  
  .status-options {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    
    .status-option {
      display: flex;
      align-items: center;
      padding: 24rpx;
      border-radius: 12rpx;
      background-color: #f8f9fa;
      
      .status-desc {
        margin-left: 24rpx;
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}
</style>